(function($) {

	$(window).ready(function() {
		$('#bc form').submit(function() {
			$(this).attr('action', '#' + $('#bc input.urn').val());
		});
		$('#bc form .buttonDelete').click(function() {
			var urn = $('#bc input.urn').val();
			$.ajax({
				type: 'delete',
				url: urn,
				complete: function() {
					$(window).hashchange();
				}
			});
		});
		$('#node [type="button"]').click(function() {
			$.ajax({
				type : 'put',
				url : $('#bc input.urn').val(),
				contentType : $('#node [type="text"]').val(),
				data : $('#node textarea').val(),
				success : function() {
					$(window).hashchange();
				}
			});
		});
		$(window).hashchange();
	});

	Restitory = {};
	Restitory.adm = {};

	Restitory.adm.index = function() {
		var urn = location.hash;
		if (urn) {
			urn = urn.substring(1);
		}
		if (!urn) {
			location.hash = '#/';
		}
		$('#bc input.urn').val(urn);

		Restitory.adm.urn = urn;
		Restitory.adm.childs();
		Restitory.adm.node();
	}

	Restitory.adm.childs = function() {
		$('#childs ul li').remove();
		var parts = Restitory.adm.urn.split('/');
		parts.pop();
		parts = parts.join('/');
		if (!parts) {
			parts = '/';
		}
		$('#childs ul').append('<li><a href="#' + parts + '">..</a></li>');

		$.getJSON('/_/query?f=parents:EQ:"' + Restitory.adm.urn + '"&s=parents:ASC',
				function(list) {
					for ( var i in list) {
						var path = list[i];
						$('#childs ul').append(
								'<li><a href="#' + path + '">' + path
										+ '</a></li>');
					}
				});
	}

	Restitory.adm.node = function() {
		$.ajax({
			type: 'GET', 
			url: Restitory.adm.urn,
			dataType: 'text',
			success: function(result, message, resp) {
				$(".status").html(resp.status + " " + message);
				$("#node [type='text']").val(resp.getResponseHeader('Content-Type'));
				$('#node textarea').val(result);
			},
			error: function(resp, status, message) {
				$(".status").html(resp.status + " " + message);
				$("#node [type='text']").val('');
				$('#node textarea').val('');
			},
		});
	}
})(jQuery);